﻿using System;
using System.Data;
using System.IO;
using SLS.DataBase;
using SLS.ExClassLib.Events;
using SLS.ExClassLib.Helpers;
using SLS.ExClassLib.Message;
namespace LanSunERP
{ 
    public partial class ERPBLayerService 
    {
        public DataSet GetDataBySM(DataSet dsSource, string mSM, string TBNAME, MessageEx BaseMessage)
        {
            MessageEx msgX = null;
            try
            {
                DataSet dsRequest = new DataSet();
                MessageEx msgRequest = new MessageEx(BaseMessage);
                DataTable dtQueryCond = null;
                DataRow dwQueryCond = null;
                if (dsSource.Tables.Contains(TBNAME + "QueryCond"))
                {
                    dtQueryCond = dsSource.Tables[TBNAME + "QueryCond"];

                }
                else
                {
                    dtQueryCond = new DataTable(TBNAME + "QueryCond");
                    dtQueryCond.Columns.Add("QueryType", System.Type.GetType("System.String"));
                    dtQueryCond.Columns.Add("CONDTYPE", System.Type.GetType("System.String"));
                    dtQueryCond.Columns.Add("SM", System.Type.GetType("System.String"));
                }
                dwQueryCond = dtQueryCond.NewRow();
                dwQueryCond["QueryType"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_" + TBNAME + "_SM";
                dwQueryCond["SM"] = mSM;
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msgRequest.setEvent = dsRequest;
                msgRequest.JobID = "OnQuery" + TBNAME;
                msgX = AskService(msgRequest);
                if (msgX.setEvent.Tables.Contains(TBNAME))
                {
                    dsSource.Merge(msgX.setEvent.Tables[TBNAME].Select());
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dsSource;
        }
        public SLDBSET GetTableStructure(SLDBSET dsSource, string TBNAME, MessageEx BaseMessage)
        {
            try
            {
                MessageEx msgX = null;
                DataSet dsRequest = new DataSet();
                MessageEx msgRequest = new MessageEx(BaseMessage);
                DataTable dtQueryCond = null;
                DataRow dwQueryCond = null;

                dtQueryCond = new DataTable(TBNAME);
                dtQueryCond.Columns.Add("SM", System.Type.GetType("System.String"));
                dtQueryCond.Columns.Add("QueryType", System.Type.GetType("System.String"));
                dtQueryCond.Columns.Add("CONDTYPE", System.Type.GetType("System.String"));

                dwQueryCond = dtQueryCond.NewRow();
                dwQueryCond["QueryType"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "DB_" + TBNAME + "_STRUCTURE";
                dwQueryCond["SM"] = msgRequest.SM;
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msgRequest.setEvent = dsRequest;
                msgRequest.JobID = "OnQueryTableStructure";
                msgX = AskService(msgRequest);
                if (msgX.setEvent.Tables.Contains(TBNAME))
                {
                    dsSource = (SLDBSET)ImportDataTable(dsSource, msgX.setEvent.Tables[TBNAME]);
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dsSource;
        }
        public DataTable GetTableList2Agent(DataSet dsSource, string mSM,
            string mAgentID, string TaskType
            , MessageEx BaseMessage
            )
        {
            MessageEx msgX = null;
            DataTable dtTableList2Agent = new DataTable();
            try
            {
                DataSet dsRequest = new DataSet();
                MessageEx msgRequest = new MessageEx(BaseMessage);
                DataRow dwQueryCond = null;
                if (dsSource.Tables.Contains("TableList2AgentQueryCond"))
                {
                    dwQueryCond = dsSource.Tables["TableList2AgentQueryCond"].NewRow();
                    dwQueryCond["QueryType"] = "QueryOnly";
                    dwQueryCond["CONDTYPE"] = "IX_TableList2Agent_TaskType";
                    dwQueryCond["SM"] = mSM;
                    dwQueryCond["AgentID"] = mAgentID;
                    dwQueryCond["Task"] = TaskType;
                    dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                    msgRequest.setEvent = dsRequest;
                    msgRequest.JobID = "OnQueryTableList2Agent";
                    msgX = AskService(msgRequest);
                    if (msgX.setEvent.Tables.Contains("TableList2Agent"))
                    {
                        dtTableList2Agent = msgX.setEvent.Tables["TableList2Agent"].Copy();
                    }
                }
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dtTableList2Agent;
        }
        public DataTable GetTableList2Agent(DataSet dsSource, string TaskType, string TBNAME)
        {
            DataTable dtTableList2Agent = new DataTable();
            MessageEx msgX = null;
            MessageEx msgRequest = new MessageEx(BaseMessage);
            try
            {
                DataSet dsRequest = new DataSet();
                msgRequest = new MessageEx(BaseMessage);
                DataRow dwQueryCond = dsSource.Tables["TableList2AgentQueryCond"].NewRow();
                dwQueryCond["QueryType"] = "QueryOnly";
                dwQueryCond["CONDTYPE"] = "IX_TableList2Agent_TaskTypeByTableName";
                dwQueryCond["SM"] = "1";
                dwQueryCond["AgentID"] = "ERPBLayerService";
                dwQueryCond["Task"] = TaskType;
                dwQueryCond["TBNAME"] = TBNAME;
                dsRequest = (DataSet)ImportDataTable(dsRequest, dwQueryCond);
                msgRequest.setEvent = dsRequest;
                msgRequest.JobID = "OnQueryTableList2Agent";
                msgX = AskService(msgRequest);
                if (msgX.setEvent.Tables.Contains("TableList2Agent"))
                {
                    dtTableList2Agent = msgX.setEvent.Tables["TableList2Agent"].Copy();
                }

            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return dtTableList2Agent;
        }

        private void UpdateTheDataSet()
        {
            try
            {
                MessageEx msgX = null;
                //Read all the tableStructure
                DataSet dsAgent = (DataSet)dicDsParameters[BaseMessage.AgentID.ToUpper()];
                string dsName = BaseMessage.AgentID;

                if (setGlobal == null)
                {
                    setGlobal = new SLDBSET();
                    setGlobal.DataSetName = dsName;
                }
                /*
                if (File.Exists(UIXMLPath))
                {
                    setGlobal.ReadXml(this.UIXMLPath);
                }*/
                #region Load all the table data
                string set2loadfile = AppXMLPath + @"Set4BL.xml";
                DataSet SetTemp = new DataSet();
                if (File.Exists(set2loadfile))
                {
                    setGlobal.ReadXml(set2loadfile);
                    //setGlobal.Merge(SetTemp);
                    //File.Delete(set2loadfile);
                }

                #endregion
                DataTable dtTableList2Agent = GetTableList2Agent(dsAgent, "9", "ERPBLayerService", "Schema", BaseMessage);
                if (dtTableList2Agent.Rows.Count > 0)
                {
                    #region GetTableStructure
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        string TBName = dwTableList2Agent["TBNAME"].ToString().Trim();
                        if (setGlobal.Tables.Contains(TBName))
                        {
                            //setGlobal.Tables[TBName].Clear();
                            //setGlobal.AcceptChanges();
                        }
                        setGlobal = this.GetTableStructure(setGlobal, TBName, BaseMessage);
                        setGlobal.AcceptChanges();
                        dwTableList2Agent["Status"] = "DELETE";
                    }
                    #endregion

                    #region delete dtTableList2Agent
                    DataSet ds2Delete = new DataSet();
                    foreach (DataRow dwTableList2Agent in dtTableList2Agent.Rows)
                    {
                        if (dwTableList2Agent["Status"].ToString().Trim() == "DELETE")
                        {
                            ds2Delete = (DataSet)ImportDataTable(ds2Delete, dwTableList2Agent);
                        }
                    }
                    ds2Delete.AcceptChanges();
                    MessageEx msgRequest = new MessageEx(BaseMessage);
                    msgRequest.JobID = "OnDeleteRecord";
                    msgRequest.setEvent = ds2Delete;
                    msgX = AskService(msgRequest);
                    #endregion

                    #region ImportData
                    //ExBasicControl.DeleteData(ds2Delete); 
                    if (setGlobal != null)
                    {
                        foreach (DataTable dtTemp in setGlobal.Tables)
                        {
                            dsAgent = (DataSet)ImportDataTable(dsAgent, dtTemp);
                        }
                    }
                    #endregion
                }
                setGlobal.WriteXml(UIXMLPath, XmlWriteMode.WriteSchema);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return;
        }
        private MessageEx AgentInitialization(MessageEx msgRequest)
        {
            MessageEx msgX = null;
            try
            { 
                msgX = msgRequest;
                string AgentID = msgRequest.AgentID.ToUpper();
                SLDBSET set4Agent = new SLDBSET();
                set4Agent.DataSetName = AgentID;
                if (!dicDsParameters.ContainsKey(AgentID))
                    dicDsParameters.Add(AgentID, set4Agent);
                DataSet setAgent = new DataSet();
                if (setGlobal != null)
                {
                    set4Agent.Merge(setGlobal);
                }
                DicGlobalPara["msgRequest"] = msgRequest;
                DicGlobalPara["dsParameters"] = set4Agent;
                string expression = "AgentID='" + AgentID + "'";
                DataRow[] Agents = set4Agent.AgentList.Select(expression);
                setAgent.Merge(Agents);
                msgX.setEvent = setAgent;
                //Tracer.Verbose("AgentInitialization", setAgent);
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
            return msgX;
        }
        #region Share
        private void TraceConfiguration()
        {
            try
            {
                //delete the old log file
                string logPath = Path.Combine(PathHelper.ApplicationPath, "\\log");
                logPath = PathHelper.ApplicationPath + "\\log\\LanSunERPBL.exe.log";
                if (File.Exists(logPath))
                    File.Delete(logPath);

                if (BLSVC.Properties.Settings.Default.UseTraceListener)
                {
                    //configure the trace
                    System.Diagnostics.Trace.AutoFlush = true;
                    System.Diagnostics.Trace.IndentSize = 2;

                    //configure the text listenner
                    System.Diagnostics.TraceListenerCollection listeners = System.Diagnostics.Trace.Listeners;
                    listeners.Add(new System.Diagnostics.TextWriterTraceListener(logPath, "LOG"));
                } 
            }
            catch (Exception ex)
            {
                Tracer.Error(ex.StackTrace, ex);
            }
        }
        private DataTable ImportDataRow(DataRow DataRowSrc)
        {
            DataTable objectTable = DataRowSrc.Table.Clone();//必须先复制表的架构，使具有相同的的列或关系！ 
            objectTable.Rows.Add(DataRowSrc.ItemArray);//在objectTable中添加一个新行，并将sourceRow的值复制进去,要求表的结构一样！

            //objectTable=DataRowSrc.Table.Copy();
            return objectTable;
        }
        private Object ImportDataTable(DataSet dtObjectDataSet, DataTable dtSourceTable)
        {
            dtObjectDataSet.Merge(dtSourceTable, true, MissingSchemaAction.Add);
            return dtObjectDataSet;
        }
        private Object ImportDataTable(DataSet dtObjectDataSet, DataRow dwSourceRecord)
        {
            DataTable dtObject;
            dtObject = this.ImportDataRow(dwSourceRecord);
            dtObjectDataSet.Merge(dtObject, true, MissingSchemaAction.Add);
            return dtObjectDataSet;
        }
        #endregion
    }
}